package com.etcn.modules.busi.order.controller;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alipay.api.internal.util.AlipaySignature;
import com.etcn.common.Enum.PayMethod;
import com.etcn.common.annotation.Manage;
import com.etcn.common.controller.BaseController;
import com.etcn.common.payment.alipay.constants.AlipayConstants;
import com.etcn.common.payment.wxpay.constants.WxPayConstants;
import com.etcn.common.payment.wxpay.util.WxPaySignature;
import com.etcn.common.payment.wxpay.util.WxPayUtil;
import com.etcn.common.utils.http.HttpTransfer;
import com.etcn.modules.busi.order.pojo.WmOrder;
import com.etcn.modules.busi.order.service.IWmOrderService;

/**
 * 订单
 *
 * @author guozc
 * @date: 2018-03-19
 */
@Controller
@RequestMapping("/v1/orders")
public class WmOrderController extends BaseController {

    private Logger controllerLogger = (Logger) LoggerFactory.getLogger("service_file_log");

    @Autowired
    private IWmOrderService wmOrderService;

    /**
     * 新增订单
     */
    @Manage
    @RequestMapping(value = "add", method = RequestMethod.POST)
    public @ResponseBody Object add(@RequestBody WmOrder wmOrder) throws Exception {
        return wmOrderService.add(wmOrder);
    }

    /**
     * 获取会员订单
     */
    @Manage
    @RequestMapping(value = "", method = RequestMethod.GET)
    public @ResponseBody Object getMemberOrders(WmOrder order) throws Exception {
        return wmOrderService.getMemberOrders(order);
    }

    /**
     * 获取订单详情
     */
    @Manage
    @RequestMapping(value = "{orderSn}", method = RequestMethod.GET)
    public @ResponseBody Object getDetail(@PathVariable("orderSn") String orderSn) throws Exception {
        return wmOrderService.getByOrderSn(orderSn);
    }
    
    /**
	 * 支付宝统一下单
	 */
    @Manage
    @RequestMapping(value = "alipayprepay", method = RequestMethod.POST)
	public @ResponseBody Object alipayPrePay(@RequestBody WmOrder order) throws Exception {
    	return wmOrderService.alipayPrePay(order.getOrderSn());
    }
	
	/**
	 * 微信统一下单
	 */
    @Manage
    @RequestMapping(value = "wxprepay", method = RequestMethod.POST)
	public @ResponseBody Object wxPrePay(@RequestBody WmOrder order) throws Exception {
    	return wmOrderService.wxPrePay(order.getOrderSn());
    }

    /**
     * 支付宝支付回调
     */
    @RequestMapping(value = "payNotify", method = RequestMethod.POST)
    public void payNotify(HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        response.setContentType("type=text/html;charset=UTF-8");
        PrintWriter wt = response.getWriter();

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        String charset = AlipayConstants.INPUT_CHARSET;
        //交易流水号
        String out_trade_no = new String(request.getParameter("out_trade_no").
                getBytes("ISO-8859-1"),charset);
        //支付金额
        String total_fee = request.getParameter("total_fee");
        String total_amount = request.getParameter("total_amount");
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").
                getBytes("ISO-8859-1"),charset);
        String[] ary = out_trade_no.split("_");
        //订单号
        String orderNumber = ary[0];

        this.controllerLogger.info("回调订单:"+out_trade_no+" trade_status:" + trade_status + 
        		" total_fee:" + total_fee+" total_amount:" + total_amount + " orderNumber:" + orderNumber);
        if(AlipaySignature.rsaCheckV1(params, AlipayConstants.rsaPublicKey, charset,AlipayConstants.SIGN_TYPE)){
            if(trade_status.equals(AlipayConstants.ALIPAY_TRADESTATUS_WAITPAY)){
                this.controllerLogger.info("等待买家付款");
                wt.write("success");
            }else if(trade_status.equals(AlipayConstants.ALIPAY_TRADESTATUS_SUCCESS)){
                this.controllerLogger.info("买家付款成功");
                WmOrder o = new WmOrder();
                o.setOrderSn(orderNumber);
                o.setPayType(PayMethod.ALIPAY.value());
                o.setPayAmount(total_amount);
                wmOrderService.payOrder(o);
                wt.write("success");
            }else if(trade_status.equals(AlipayConstants.ALIPAY_TRADESTATUS_FINISHED)){
                this.controllerLogger.info("交易已完成");
                wt.write("success");
            }else{
                wt.write("success");
            }
        }else{
            this.errorLogger.error("回调订单"+out_trade_no+"验证签名失败");
        }
    }
    
    /**
	 * 微信支付回调
	 */
    @RequestMapping(value = "wxPayNotify", method = RequestMethod.POST)
	public void wxPayNotify(HttpServletRequest request,HttpServletResponse response) 
			throws Exception {
    	//返回参数
    	String result = HttpTransfer.fetchString(request);
    	Map<String,Object> m = WxPayUtil.xmlToMap(result);
    	String[] ary = ((String)m.get("out_trade_no")).split("_");
		//订单号
		String orderNumber = ary[0];
		//付款金额
		Integer total_fee = Integer.parseInt((String)m.get("total_fee"));
		//回调签名
		String callSign = (String)m.get("sign");
    	//根据回调状态进行逻辑处理并封装返回结果
		String returnCode = (String)m.get(WxPayConstants.RETURN_CODE);
    	String result_code = (String)m.get(WxPayConstants.RESULT_CODE);
    	this.controllerLogger.info("订单回调:"+orderNumber+" return_code:"+returnCode+" result_code:"+result_code);
    	Map<String,Object> retMsg = new HashMap<String,Object>();
    	if(returnCode.equals(WxPayConstants.SUCCESS)){
    		//验证签名
    		if(WxPaySignature.sign(m).equals(callSign)){
    			if(result_code.equals(WxPayConstants.SUCCESS)){
            		retMsg.put(WxPayConstants.RETURN_CODE, WxPayConstants.SUCCESS);
            		retMsg.put(WxPayConstants.RETURN_MSG, WxPayConstants.OK);
            		//业务逻辑处理
            		WmOrder o = new WmOrder();
            		o.setOrderSn(orderNumber);
                    o.setPayType(PayMethod.WXPAY.value());
                    o.setPayAmount(String.valueOf(total_fee));
                    wmOrderService.payOrder(o);
            	}else{
            		retMsg.put(WxPayConstants.RETURN_CODE, WxPayConstants.FAIL);
            	}
    		}else{
    			this.errorLogger.error("订单回调:"+orderNumber+" 验证签名失败。");
    		}
    	}else{
    		retMsg.put(WxPayConstants.RETURN_CODE, WxPayConstants.FAIL);
    	}
    	response.setContentType("type=text/html;charset=UTF-8"); 
    	PrintWriter wt = response.getWriter();
    	wt.write(WxPayUtil.mapToXml(retMsg));
	}

}

